package com.yyaccp.easybuy.security.service;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class SmsService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public void send(String to, String code) {
        // 代码来自官方文档 https://doc.yuntongxun.com/p/5f0299f4a80948a1006e775e
        String serverIp = "app.cloopen.com";
        String serverPort = "8883";
        String accountSId = "你的sid";
        String accountToken = "你的token";
        String appId = "你的appid";
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        String templateId= "1";
        int exprie = 5;
        String[] datas = {code, "" + exprie};
        HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
        if("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息（map）
            HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
            Set<String> keySet = data.keySet();
            for(String key:keySet){  Object object = data.get(key); System.out.println(key +" = "+object); }
            stringRedisTemplate.opsForValue().set("login:" + to, code, exprie, TimeUnit.MINUTES);// 存储验证码
        }else{
            System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
        }
    }

    public void validate(String phoneNumber, String code) {
        if(!code.equals(stringRedisTemplate.opsForValue().get("login:" + phoneNumber))) {
            throw new BadCredentialsException("验证码错误");
        }
    }
}
